package serverClientDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;

/**
 * A text interface for the client
 * 
 * @author Chris
 */
public class ClientTextInterface implements Observer {

	Client client;
	String address;
	int port;

	/**
	 * Creates a ClientTextInterface
	 */
	public ClientTextInterface() {
		client = new Client();
		client.addObserver(this);
	}

	/**
	 * Send messages to the server
	 */
	public void run() {
		while (true) {
			String message;
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					System.in));
			try {
				message = reader.readLine();
				if (message.equalsIgnoreCase("exit")) {
					System.out.println("exiting...");
					System.exit(0);
				}
				client.sendMessage(address, port, message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Connect to the server
	 * 
	 * @param address
	 *            the server address
	 * @param port
	 *            the server port
	 * @return true if successful, false otherwise
	 */
	public void setAddress(String address, int port) {
		this.address = address;
		this.port = port;
	}

	/**
	 * Main
	 * 
	 * @param args
	 *            the server address and port
	 */
	public static void main(String args[]) {
		ClientTextInterface textInterface = new ClientTextInterface();
		if (args.length != 2) {
			System.out.println("usage: ClientTextInterface <address> <port>");
			System.exit(1);
		}
		System.out.println("starting text interface...");
		System.out.println("type text to send to server, type exit to exit:");
		textInterface.run();
	}

	/**
	 * Receive messages from the server
	 */
	@Override
	public void update(Observable o, Object arg) {
		if (arg instanceof String) {
			String message = (String) arg;
			System.out.println("server: " + message + '\n');
		}
	}
}
